﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StockWatcher
{
    public partial class FrmNote : Form
    {
        const int DEFAULT_CLOSE_TIME = 60000;
        int closeTime = 0;
        int countDown = 0;
        string title;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="closeTime">关闭时间,毫秒,如果是负数,需要手工关闭</param>
        public FrmNote(string title, string message, int closeTime = DEFAULT_CLOSE_TIME)
        {
            this.title = title;
            InitializeComponent();
            this.Text = title;
            this.txtMessageArea.Text = message;
            this.closeTime = closeTime;
            this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, Screen.PrimaryScreen.Bounds.Height - this.Height - 40);//40是大概任务栏的高度
        }

        private void frmNote_Load(object sender, EventArgs e)
        {
            if (closeTime > 0)
            {
                tmrClose.Interval = closeTime;
                tmrClose.Start();
                countDown = closeTime / 1000;
                tmrCountDown.Start();
            }
            System.Media.SystemSounds.Beep.Play();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            closeThis();
        }
        private void closeThis()
        {
            if (this.InvokeRequired)
                this.Invoke(new Action(closeThis));
            else
            {
                this.Close();
            }
        }
        public void AppendMessage(string message, int closeTime = DEFAULT_CLOSE_TIME)
        {
            this.closeTime = closeTime;
            this.txtMessageArea.Text += Environment.NewLine + message;
            tmrClose.Stop();
            tmrCountDown.Stop();
            if (this.closeTime > 0)
            {
                tmrClose.Interval = closeTime;
                tmrClose.Start();
                countDown = closeTime / 1000;
                tmrCountDown.Start();
            }
            txtMessageArea.Select(txtMessageArea.Text.Length - 1, 0);
            txtMessageArea.ScrollToCaret();
            System.Media.SystemSounds.Beep.Play();
        }

        private void tmrCountDown_Tick(object sender, EventArgs e)
        {
            showCountDown();
        }
        private void showCountDown()
        {
            if (this.InvokeRequired)
                this.Invoke(new Action(showCountDown));
            else
            {
                countDown--;
                this.Text = string.Format("{0}(还有{1}秒关闭)", this.title, countDown);
            }
        }
    }
}
